import React, { useRef, useState } from 'react'
import ReactDOM from 'react-dom'
import { Modal, Button, Form, Input, message } from 'antd'
import style from './index.module.scss'
import getName from '@/utils/mockName'
import { getToken } from '@/api'
import { storage } from '@/utils/utils'
import store from '@/utils/store'

const loginStore: {
  setShow: (...params: any) => any
  loginSuccess: (...params: any) => void
} = {
  setShow: () => {},
  loginSuccess: () => {},
}
export const checkLogin = () => {
  return new Promise((resolve, _) => {
    const token = storage.get('token')
    if (token) return resolve(undefined)
    loginStore.setShow(true)
    loginStore.loginSuccess = resolve
  })
}
function Login() {
  const formValue: any = useRef({
    nickName: '',
    contact: '',
  })

  const [show, setShow] = useState(false)
  loginStore.setShow = setShow
  const submit = async () => {
    const { status, msg, data } = await getToken(formValue.current.getFieldsValue(true))
    if (!status) return message.warn(msg)
    store.token = data.token
    storage.set('token', data.token)
    setShow(false)
    loginStore.loginSuccess()
  }

  return (
    <div>
      <Modal
        visible={show}
        title="大侠留步"
        onOk={() => {
        }}
        onCancel={() => {
        }}
        footer={null}
      >
        <Form
          ref={formValue}
          name="login"
          initialValues={{
            nickName: '',
            contact: '',
          }}
          onFinish={submit}
        >
          <Form.Item
            label=""
            name="nickName"
            rules={[{ required: true, message: '请输入尊姓大名' }]}
          >
            <Input.Search
              onSearch={() => {
                formValue.current.setFieldsValue({
                  nickName: getName(),
                })
              }}
              placeholder="尊姓大名"
              enterButton="随机"
            />
          </Form.Item>

          <Form.Item label="" name="contact" rules={[{ required: false }]}>
            <Input placeholder="联系方式(默认123456)" />
          </Form.Item>

          <Form.Item>
            <div className={style.btn_row}>
              <Button
                size="large"
                className={style.login_btn}
                type="primary"
                htmlType="submit"
              >
                提交
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

ReactDOM.render(React.createElement(Login), document.createElement('div'))
